﻿using System;
using System.Globalization;
#if NETFX_CORE
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
#else
using System.Windows;
using System.Windows.Data;
#endif

namespace FreshMeat.Xaml
{
#if !SILVERLIGHT && !NETFX_CORE
   [System.Windows.Markup.MarkupExtensionReturnType(typeof(IValueConverter))]
#endif
#if NETFX_CORE
   public class VisibilityConverterExtension : IValueConverter
   {
#else
   public class VisibilityConverterExtension : System.Windows.Markup.MarkupExtension, IValueConverter
   {
      static VisibilityConverterExtension converter;

      public override object ProvideValue(IServiceProvider serviceProvider)
      {
         return converter ?? (converter = new VisibilityConverterExtension());
      }
#endif

#if NETFX_CORE
      public object Convert(object value, Type targetType, object parameter, string culture)
#else
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
#endif
      {
         bool actualValue;
         if (value is bool)
            actualValue = (bool)value;
         else if (value is int)
            actualValue = (int)value != 0;
         else if (value is long)
            actualValue = (long)value != 0;
         else if (value is double)
            actualValue = Math.Abs((double)value - 0.0) > 0.0;
         else
            actualValue = value != null;

         if (parameter != null && parameter.ToString().ToLower() == "inverse")
            actualValue = !actualValue;
         else if (parameter != null && parameter.ToString().ToLower() != "normal")
            throw new ArgumentException("Valid values for parameter are 'inverse' or 'normal'.");

         return actualValue ? Visibility.Visible : Visibility.Collapsed;
      }

#if NETFX_CORE
      public object ConvertBack(object value, Type targetType, object parameter, string culture)
#else
      public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
#endif
      {
         var visibility = (Visibility)value;

         if (parameter == null || parameter.ToString().ToLower() == "normal")
            return (visibility == Visibility.Visible);

         if (parameter.ToString().ToLower() == "inverse")
            return (visibility != Visibility.Visible);

         throw new ArgumentException("Valid values for parameter are 'inverse' or 'normal'.");
      }
   }
}
